import React, {
  Fragment,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";
/** useref https://juejin.cn/post/6996171186719686693 */
/** 公共配置的状态放头上，利用effect 上状态发生变化,然后监听某个参数,相当于递归 */
const Case = () => {
  const [loading, setLoading] = useState<boolean>(true);

  const [error, setError] = useState(false);

  const [time, setTime] = useState(3);

  const handle = useCallback(() => {
    setTimeout(() => {
      setError(true);
    }, 1000);
  }, []);

  const ref = useRef<number | null>(null);

  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  }, []);

  const handleLoad = useCallback(() => {
    setTimeout(() => {
      setError(true);
    }, 1000);
  }, []);

  const handleError = useCallback(() => {
    setError(true);
  }, []);
  /** 当依赖发生变化，useEffect会重复调用*/
  const handleTimeout = useCallback(() => {
    ref.current = window.setTimeout(() => {
      if (time === 0) {
        console.log("0" + time);
        return;
      } else {
        setTime((t) => t - 1);
        console.log(time);
      }
    }, 1000);
  }, [time]);

  useEffect(() => {
    if (error) {
      handleTimeout();
    }
  }, [error, handleTimeout]);

  useEffect(() => {
    return () => {
      if (time) {
        ref.current = null;
      }
    };
  }, []);

  const addTime = useCallback(() => {
    setTime((value) => value + 1);
  }, [time]);

  /** 用settimeouter 有定时器任务。 拿到值是旧值，必须要用ref 相当于全局配置。*/
  const getValue = useCallback(() => {
    setTimeout(() => {
      alert(time);
    }, 2000);
  }, [time]);

  if (error) {
    return <span>error....</span>;
  } else {
    return (
      <Fragment>
        {loading && <span>loading</span>}

        <div onLoad={handleLoad} onError={handleError} onClick={handle}>
          内容
        </div>
        <button onClick={addTime}>{time}</button>
        <button onClick={getValue}>获取time</button>
      </Fragment>
    );
  }
};

export default Case;
